
class Node(object):
    '''
    节点类
    '''
    def __init__(self, item):
        self.item = item
        self.next = None
        self.prev = None

class DoubleLinkList(object):
    '''
    双链表类
    '''
    def __init__(self, node=None):
        self.__head = node

    def is_empty(self):
        '''链表是否为空'''
        return self.__head is None

    def length(self):
        '''链表的长度'''
        # cur游标，用来移动遍历节点
        cur = self.__head
        # count记录数量
        count = 0
        while cur != None:
            count += 1
            cur = cur.next
        return count

    def travel(self):
        '''遍历整个链表'''
        cur = self.__head
        while cur != None:
            print(cur.item, end=' ')
            cur = cur.next
        print(end='\n')

    def append(self, item):
        '''链表尾部添加元素'''
        node = Node(item)
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            while cur.next != None:
                cur = cur.next
            cur.next = node
            node.prev = cur

    def add(self, item):
        '''链表头部添加元素'''
        node = Node(item)
        if self.is_empty():
            self.__head = node
        else:
            cur = self.__head
            self.__head = node
            node.next = cur
            cur.prev = node

    def insert(self, index, item):
        '''插入元素'''
        node = Node(item)
        if self.is_empty():
            self.__head = node
        elif index <= 0:
            self.add(item)
        elif index >= self.length():
            self.append(item)
        else:
            cur = self.__head
            count = 0
            while count < index-1:
                count += 1
                cur = cur.next
            node.next = cur.next
            cur.next.prev = node
            cur.next = node
            node.prev = cur

    def search(self, item):
        '''查找元素'''
        cur = self.__head
        while cur != None:
            if cur.item == item:
                return True
            else:
                cur = cur.next
        return False

    def remove(self, item):
        '''删除元素'''
        cur = self.__head
        while cur != None:
            if cur.item == item:
                # 先判断此节点是否是头节点
                if cur == self.__head:
                    self.__head = cur.next
                    cur.next.prev = None
                else:
                    cur.prev.next = cur.next
                    if cur.next:
                        cur.next.prev = cur.prev
                return item
            else:
                cur = cur.next


if __name__ == '__main__':
    ll = DoubleLinkList()
    print(ll.is_empty())
    print(ll.length())

    ll.append(1)
    ll.append(13)
    ll.append(16)
    ll.append(35)
    ll.append(2)
    ll.add(1000)
    ll.insert(7, 50)
    print(ll.is_empty())
    print(ll.length())
    ll.travel()
    print(ll.search(1000))
    ll.remove(1000)
    ll.travel()


